package com.yeskery.nut.cloud.feign;

import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.extend.responsive.ResponsiveConvert;

import java.lang.reflect.Type;

/**
 * Feign 响应转换<code>application/json</code>实现类
 * @author YESKERY
 * 2024/9/19
 */
public class ApplicationJsonFeignResponseConvert implements FeignResponseConvert {

    /** 应用上下文 */
    private final ApplicationContext applicationContext;

    /** 响应转换对象 */
    private volatile ResponsiveConvert responsiveConvert;

    /**
     * 构造Feign 响应转换<code>application/json</code>实现对象
     * @param applicationContext 应用上下文
     */
    public ApplicationJsonFeignResponseConvert(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public <T> T convert(String data, Type type) {
        return getResponsiveConvert().convertFromStringByType(data, type);
    }

    /**
     * 获取响应转换对象
     * @return 响应转换对象
     */
    private ResponsiveConvert getResponsiveConvert() {
        if (responsiveConvert == null) {
            synchronized (this) {
                if (responsiveConvert == null) {
                    responsiveConvert = applicationContext.getBean(ResponsiveConvert.class);
                }
            }
        }
        return responsiveConvert;
    }
}
